package com.ssfeng.proxy2;

import cn.hutool.core.io.FileUtil;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * Created by liyuhang on 2020-09-10.
 */
public class MyProxy {
    public static final String ln = "\r\n";

//    private static  MyClassLoader myClassLoader = new MyClassLoader();

    public static Object newProxyInstance(MyClassLoader object, Class<?>[] interfaces, MyInvocationHandler h) {
        try {
            //1 java源码
            String src = src(interfaces);

            //2. 源码输出到java文件中，并保存到本地
            File file = disk(src);

            //3、将java文件编译成class文件
            compile(file);

            //4.1 使用自定义加载器将class加载进jvm里
            Class proxyClass = object.findClass("$Proxy0");

            //5、获取构造方法
            Constructor constructor = proxyClass.getConstructor(MyInvocationHandler.class);

            //构造代理对象
            return constructor.newInstance(h);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 结构固定
     * @param interfaces
     * @return
     */
    private static String src(Class<?>[] interfaces) {
        // 找包名
        String packageName = interfaces[0].getPackage().getName();

        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageName + ";" + ln);
        sb.append("import java.lang.reflect.Method;" + ln);
        sb.append("public class $Proxy0 implements " + interfaces[0].getName() + "{" + ln);
        sb.append("private MyInvocationHandler h;"+ln);
        sb.append("public $Proxy0(MyInvocationHandler h) { " + ln);
        sb.append("this.h = h;"+ln);
        sb.append("}" + ln);
        for (Method m : interfaces[0].getMethods()) {
            sb.append("public " + m.getReturnType().getName() + " "
                    + m.getName() + "() {" + ln);
            sb.append("try{" + ln);
            sb.append("Method m = " + interfaces[0].getName()
                    + ".class.getMethod(\"" + m.getName()
                    + "\",new Class[]{});" + ln);
            sb.append("this.h.invoke(this,m,null);" + ln);
            sb.append("}catch(Throwable e){" + ln);
            sb.append("e.printStackTrace();" + ln);
            sb.append("}"+ln);
            sb.append("}"+ln);
        }
        sb.append("}" + ln);
        System.out.println(sb.toString());
        return sb.toString();
    }

    /**
     * 源码保存到磁盘
     * @param classSrc
     * @return
     */
    public static File disk(String classSrc) {
        String filePath = MyProxy.class.getResource("").getPath() + "$Proxy0.java";
        //此处借助hutool工具
        return FileUtil.writeBytes(classSrc.getBytes(), filePath);
    }

    /**
     * 编译java文件
     * @param file
     */
    public static void compile(File file) {
        try {
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager manage = compiler.getStandardFileManager(null, null, null);
            Iterable iterable = manage.getJavaFileObjects(file);
            JavaCompiler.CompilationTask task = compiler.getTask(null, manage, null, null, null, iterable);
            task.call();
            manage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
